package main

import (
	"encoding/json"
	//"fmt"
	"io/ioutil"
)

type AddressBook interface {
	Load(string) error //加载map.json
	Get(string) ([]string, []string)
	//TODO: keep status, ignore error hosts
}

type SimpleAddressBook struct {
	fn       string
	addreses map[string]string
	stdCount int
	fbkCount int
}

var sc, fc int = 7, 1 //fc这里是到mixfs里面查，对应的状态是2

func NewSimpleAddressBook(fn string) (*SimpleAddressBook, error) {
	r := SimpleAddressBook{stdCount: sc, fbkCount: fc}
	err := r.Load(fn)
	return &r, err
}

func (s *SimpleAddressBook) Load(fn string) error {
	c, err := ioutil.ReadFile(fn) //读取map.json
	if err != nil {
		return err
	}
	err = json.Unmarshal(c, &s.addreses)
	if err != nil {
		return err
	}

	s.fn = fn //只是读取的配置文件
	s.stdCount = sc
	s.fbkCount = fc

	return nil
}

func (s *SimpleAddressBook) randomAddresses(count int, excludeAddresses []string) (ret []string) {
	for _, v := range s.addreses { //在这么多地址中
		contains := false //标志位，初始为false

		for _, e := range excludeAddresses { //另一个
			if e == v {
				contains = true
				break
			}
		}

		if !contains { //如果没有相等的话
			ret = append(ret, v)
		}

		if len(ret) == count { //长度够了就好
			return
		}
	}
	return
}

func (s *SimpleAddressBook) Get(id string) (std []string, fbk []string) {
	addr, ok := s.addreses[id]

	if !ok || id == "" { //找不到或者id没有
		//std =  s.randomAddresses(s.stdCount,nil)
		std = s.randomAddresses(s.stdCount, nil)

	} else {
		std = append(std, addr) //如果有这个id的话就维护一个std，找到
	}
	fbk = s.randomAddresses(s.fbkCount, nil)
	return
}
